﻿using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

public class NetModuleBase : MonoBehaviour
{

    /// <summary>
    /// 服务器IP
    /// </summary>
    [SerializeField]
    protected string ip = "127.0.0.1";
    /// <summary>
    /// 服务器端口
    /// </summary>
    [SerializeField]
    protected string port = "5555";

    /// <summary>
    /// 是否使用粘包分包解析,是否使用4字节长度解析，发送
    /// </summary>
    [SerializeField]
    protected bool isPacketDecode = true;

    /// <summary>
    /// 待处理事件列表，跨线程
    /// </summary>
    protected List<CoreEvent> eventList = new List<CoreEvent>();

    /// <summary>
    /// 需要发送的消息队列
    /// </summary>
    protected List<byte[]> sendList = new List<byte[]>();


    // Update is called once per frame
    protected virtual void Update()
    {
        HandleEventList();
        SendAllMsg();
    }

    /// <summary>
    /// 处理所有事件
    /// </summary>
    protected virtual void HandleEventList()
    {
        if (eventList.Count <= 0) return;

        //复制完参数释放锁
        CoreEvent[] ces = null;
        lock (eventList)
        {
            ces = eventList.ToArray();
            eventList.Clear();
        }

        for (int i = 0; i < ces.Length; i++)
        {
            CoreEvent ce = ces[i];
            OnCoreEvent(ce);
        }
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    protected virtual void SendAllMsg() { }

    /// <summary>
    /// 添加到事件队列
    /// </summary>
    /// <param name="coreEvent"></param>
    public void AddEvent(CoreEvent coreEvent)
    {
        lock (eventList)
        {
            eventList.Add(coreEvent);
        }
    }
   

    #region 处理所有消息
    /// <summary>
    /// 所有消息事件
    /// </summary>
    /// <param name="ce"></param>
    private void OnCoreEvent(CoreEvent ce)
    {

        switch (ce.eventType)
        {
            case NetEventType.COMM_RECEIVE_MESSAGE:
                byte[] data = ce.data;
                if(ce.sender.IsServer)
                {
                    SS_ReceiveMessage(data, ce.sender);
                }
                else
                {
                    SC_ReceiveMessage(data);
                }
                break;
            case NetEventType.COMM_IP_FORMAT_ERROR:
                //IP地址格式不正确
                Comm_IPEndPointError("IP地址格式不正确");
                break;

            case NetEventType.COMM_PORT_FOMMAT_ERROR:
                //Port格式不正确
                Comm_IPEndPointError("Port格式不正确");
                break;

            case NetEventType.COMM_PORT_SCOPE_ERROR:
                //Port范围不正确
                Comm_IPEndPointError(ce.log);
                break;

            case NetEventType.COMM_START_ASYNC_RECEIVE_THREAD_FAILED:
                //启动异步接收线程失败
                Comm_SARThreadFailed(ce.log);
                break;

            case NetEventType.COMM_DISCONNECT_INITIATIVE:
                //主动断开连接
                if(ce.sender != null)
                {
                    SS_Disconnect("客户端主动断开", ce.sender);
                }
                else
                {
                    SC_Disconnect("断开连接");
                }
                break;

            case NetEventType.COMM_DISCONNECT_EXCEPTION:
                //网络异常 断开连接
                if (ce.sender != null)
                {
                    SS_Disconnect(ce.log, ce.sender);
                }
                else
                {
                    SC_Disconnect(ce.log);
                }
                break;

            case NetEventType.SS_SERVER_ALREADY_EXISTS:
                //服务器已经存在
                SS_ServerStartFailed(ce.log);
                break;

            case NetEventType.SS_SERVER_START_SUCCESS:
                //服务器启动成功
                SS_ServerStartSuccess(ce.log);
                break;

            case NetEventType.SS_SERVER_START_FAILED:
                //服务器启动失败
                SS_ServerStartFailed(ce.log);
                break;

            case NetEventType.SS_CLOSE_SERVER:
                //服务器关闭
                SS_CloseServer(ce.log);
                break;

            case NetEventType.SS_REMOVE_CLIENT_FAILED:
                //从客户端列表移除出错 不存在当前用户
                NetCore.LogWarning("从客户端列表移除出错 不存在当前用户");
                break;

            case NetEventType.SS_CLIENT_CONNECT_SUCCESS:
                //客户端连接成功
                SS_ClientConnectSuccess(ce.sender);
                break;

            case NetEventType.SS_CLIENT_CONNECT_FAILED:
                //客户端连接失败
                SS_ClientConnectFailed(ce.log);
                break;
    


          
            case NetEventType.SC_BEGIN_CONNECT:
                //开始连接服务器
                SC_BeginConnect();
                break;

            case NetEventType.SC_CONNECT_TIMEOUT:
                //连接超时
                SC_ConnectFailed("连接超时");
                break;

            case NetEventType.SC_CONNECT_EXCEPTION:
                //连接服务器异常
                SC_ConnectFailed(ce.log);
                break;

            case NetEventType.SC_CONNECT_SUCCESS:
                //连接服务器成功
                SC_ConnectSuccess();
                break;



            default:
                NetCore.Log("未处理：" + ce.eventType);
                break;
        }
    }
    #endregion

   

    /// <summary>
    /// IP/Port错误
    /// </summary>
    /// <param name="msg"></param>
    protected virtual void Comm_IPEndPointError(string msg) { }

    /// <summary>
    /// 启动异步接受线程失败
    /// </summary>
    /// <param name="msg"></param>
    protected virtual void Comm_SARThreadFailed(string msg) { }

    /// <summary>
    /// 断开连接
    /// </summary>
    /// <param name="msg">断开详情</param>
    /// <param name="cp">发送者</param>
    protected virtual void SS_Disconnect(string msg, ClientBase sender) { }


    /// <summary>
    /// 收到消息
    /// </summary>
    /// <param name="msg">真正的数据</param>
    /// <param name="sender">发送者</param>
    protected virtual void SS_ReceiveMessage(byte[] msg, ClientBase sender) { }

    /// <summary>
    /// 服务器启动失败
    /// </summary>
    /// <param name="msg"></param>
    protected virtual void SS_ServerStartFailed(string msg) { }


    /// <summary>
    /// 服务器启动成功
    /// </summary>
    /// <param name="msg"></param>
    protected virtual void SS_ServerStartSuccess(string msg) { }

    /// <summary>
    /// 服务器关闭
    /// </summary>
    /// <param name="msg"></param>
    protected virtual void SS_CloseServer(string msg) { }

    /// <summary>
    /// 客户端连接成功
    /// </summary>
    /// <param name="cp"></param>
    protected virtual void SS_ClientConnectSuccess(ClientBase sender) { }

    /// <summary>
    /// 客户端连接失败
    /// </summary>
    /// <param name="msg"></param>
    protected virtual void SS_ClientConnectFailed(string msg) { }



    /// <summary>
    /// 断开连接
    /// </summary>
    /// <param name="msg">断开详情</param>
    /// <param name="cp">发送者</param>
    protected virtual void SC_Disconnect(string msg) { }


    /// <summary>
    /// 收到消息
    /// </summary>
    /// <param name="msg">真正的数据</param>
    /// <param name="sender">发送者</param>
    protected virtual void SC_ReceiveMessage(byte[] msg) { }


    /// <summary>
    /// 开始连接服务器
    /// </summary>
    protected virtual void SC_BeginConnect() { }

    /// <summary>
    /// 连接服务器失败
    /// </summary>
    /// <param name="msg"></param>
    protected virtual void SC_ConnectFailed(string msg) { }

    /// <summary>
    /// 连接服务器成功
    /// </summary>
    protected virtual void SC_ConnectSuccess() { }
}
